<template>
    <el-row :gutter="10" class="row1">
        <el-col :span="6">
            <div style="width: 100%; height: 100px">
                <span
                    ><el-icon><UserFilled color="#008EF0" :size="40" /></el-icon
                ></span>
                <span style="position: relative;">
                    <p>会员总数</p>
                    <p>{{ userNum }} </p> 
                    <span  style="color: green; position: absolute;right: -100px;top: 0;"></span>
                </span>
            </div>
        </el-col>
        <el-col :span="6">
            <div style="width: 100%; height: 100px">
                <span
                    ><el-icon><Tickets color="#008EF0" :size="40" /></el-icon
                ></span>
                <span style="position: relative;">
                    <p>订单总数</p>
                    <p>{{ totalOder }} </p> 
                    <span  style="color: green; position: absolute;right: -100px;top: 0;"></span>
                </span>
            </div>
        </el-col>
        <el-col :span="6">
            <div style="width: 100%; height: 100px">
                <span
                    ><el-icon><GoldMedal color="#008EF0" :size="40" /></el-icon
                ></span>
                <span style="position: relative;">
                    <p>销售总额</p>
                    <p>{{ totalPrice }} </p> 
                    <span  style="color: green; position: absolute;right: -100px;top: 0;"></span>
                </span>
            </div>
        </el-col>
        <el-col :span="6">
            <div style="width: 100%; height: 100px">
                <span
                    ><el-icon><Coin color="#008EF0" :size="40" /></el-icon
                ></span>
                <span style="position: relative;">
                    <p>未读消息</p>
                    <p>{{ unreadNum }} </p> 
                    <span  style="color: green; position: absolute;right: -100px;top: 0;"></span>
                </span>
            </div>
        </el-col>
    </el-row>
    <el-row :gutter="10" class="row2">
        <el-col :span="12">
            <div id="main" style="width: 100%; height: 300px"></div>
        </el-col>
        <el-col :span="12">
            <div id="category" style="width: 100%; height: 300px"></div>
        </el-col>
    </el-row>
    <el-row :gutter="10" class="row3">
        <el-col :span="12">
            <!-- 表格 -->
            <el-table :data="userList" style="width: 100%">
                <el-table-column label="序列号" prop="id" width="120"></el-table-column>
                <el-table-column
                    label="操作员名称"
                    prop="username"
                    width="150"
                ></el-table-column>
                <el-table-column
                    label="操作员权限等级"
                    prop="level"
                    width="180"
                ></el-table-column>
                <el-table-column
                    label="操作日期"
                    prop="date"
                    width="450"
                ></el-table-column>
                <el-table-column label="操作" prop="action"></el-table-column>
            </el-table>
        </el-col>
        <el-col :span="12">
            <div>顶级销售产品</div>
            <div class="salesList">
                <div class="salesBox" v-for="item in goodRandList" :key="item.id">
                    <div class="left">
                        <img style="height: 80px; width: 80px;" :src="'http://localhost:3000/test/pic?img=' +item.img_url" alt="1">
                    </div>
                    <div class="right">
                        <div>{{ item.product }}</div>
                        <div>${{ item.price }}</div>
                        <div>销量：{{ item.sales_volume }}</div>
                    </div>
                </div>
            </div>
        </el-col>
    </el-row>

</template>

<script lang="ts" setup>
import { UserFilled, Tickets, Coin, GoldMedal } from '@element-plus/icons-vue'
import axios from 'axios'
// * 表示导入所有，as 别名
import * as echarts from 'echarts'
// import { RequestCatgoryList } from '@/api/index'
import { onMounted, ref } from 'vue'
import { useAccountStore } from '@/stores/user'
let categoryList = [] //产品分类

// 获取订单信息 
const orderlist = ref('')
const totalPrice = ref('')
const totalPriceAdd = ref('')
const totalOder = ref('')
const totalOderAdd = ref('')
const getOderList = async ()=>{
    const res = await axios({
        method: 'get',
        url: 'http://localhost:3000/goods/orderlist',
        params:{
            pageSize:200
        }
    })
    const {code,info} = res.data
    if(code === 1){
        orderlist.value = info.list
        totalPrice.value = orderlist.value.reduce(((pr,cr)=>pr+cr.total_price),0)
        totalOder.value = info.total
        
    }
}
getOderList()
// 获取用户信息 
const userNum = ref('')
const getUserList = async ()=>{
    const res = await axios({
        method: 'get',
        url: 'http://localhost:3000/users/list',
        params:{
            pageSize:200
        }
    })
    const {code,info} = res.data
    if(code === 1){
        userNum.value = info.total
    }
}
getUserList()
// 获取消息信息 
const unreadNum = ref('')
const getMessageList = async ()=>{
    let accountStore = useAccountStore()
    const res = await axios({
        method: 'get',
        url: 'http://localhost:3000/message/state',
        params: {
            user: accountStore.account.username,
        },
    })
    const { code, info } = res.data
    if (code === 1) {
        unreadNum.value = JSON.parse(info[0].message).filter(item=>item.state == 0).length
    }
}
getMessageList()

const getCategoryList = async () => {
    // .... 待完成
    drawCategoryBar()
}
//右侧ec
const drawCategoryBar = () => {
    // 1.初始化echarts
    const echart = echarts.init(document.getElementById('category'))
    // 2. 图表数据配置
    // const option = {
    //     title: {
    //         text: '产品分类数量统计',
    //     },
    //     legend: {
    //         data: ['分类'],
    //     },
    //     xAxis: {
    //         data: categoryX,
    //     },
    //     yAxis: {},
    //     series: [
    //         {
    //             name: '分类',
    //             type: 'bar', // 柱状图
    //             data: categoryData,
    //         },
    //     ],
    // }
    const option = {
        title: {
            text: '商品分类变化饼图',
            left: 'center',
        },
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)',
        },
        legend: {
            orient: 'vertical',
            left: 'left',
            data: ['早餐分类', '午餐分类', '晚餐分类'],
        },
        series: [
            {
                name: '分类统计',
                type: 'pie',
                radius: '55%',
                center: ['50%', '60%'],
                data: [
                    // { value: 335, name: '直接访问' },
                    { value: 135, name: '午餐分类' },
                    { value: 148, name: '晚餐分类' },
                    { value: 334, name: '早餐分类' },
                ],
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)',
                    },
                },
            },
        ],
    }
    let currentIndex = -1

    setInterval(function () {
        var dataLen = option.series[0].data.length
        // 取消之前高亮的图形
        echart.dispatchAction({
            type: 'downplay',
            seriesIndex: 0,
            dataIndex: currentIndex,
        })
        currentIndex = (currentIndex + 1) % dataLen
        // 高亮当前图形
        echart.dispatchAction({
            type: 'highlight',
            seriesIndex: 0,
            dataIndex: currentIndex,
        })
        // 显示 tooltip
        echart.dispatchAction({
            type: 'showTip',
            seriesIndex: 0,
            dataIndex: currentIndex,
        })
    }, 1000)
    // 3. 设置配置
    echart.setOption(option)
}
//左侧ec
const drawBar = () => {
    // 打开一个 web socket，设定websocket服务器地址和端口
    var ws = new WebSocket('ws://127.0.0.1:8081')

    //开启连接open后客户端处理方法
    ws.onopen = function () {
        // Web Socket 已连接上，在页面中显示消息
        console.log('当前客户端已经连接到websocket服务器')
        ws.send('start')
    }
    // 初始化echarts
    // const echart = echarts.init(document.getElementById('main'))
    // echart.setOption({
    //     title: {
    //         text: '2022年产品销量',
    //     },
    //     legend: {
    //         data: ['销量', '价格'],
    //     },
    //     xAxis: {
    //         data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子'],
    //     },
    //     yAxis: {},
    //     series: [
    //         {
    //             name: '销量',
    //             type: 'bar', // 柱状图
    //             data: [5, 20, 36, 10, 10, 20],
    //         },
    //         {
    //             name: '价格',
    //             type: 'bar', // 柱状图
    //             data: [9.9, 26.9, 38, 35, 43, 58],
    //         },
    //     ],
    // })
    // 基于准备好的dom，初始化echarts实例
    var myChart = echarts.init(document.getElementById('main'))

    // 指定图表的配置项和数据
    var option = {
        title: {
            text: '商品价格实时变化详情',
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                animation: false,
                label: {
                    backgroundColor: '#505765',
                },
            },
        },
        legend: {
            data: ['价格','销量'],
        },
        xAxis: {
            data: ['番茄炒蛋', '土豆炖肉2', '土豆炖肉', '油条', '黑椒牛肉', '回锅肉'],
        },
        yAxis: {},
        series: [
            {
                name: '价格',
                type: 'bar',
                data: [5, 20, 36, 10, 10, 20],
            },
            {
                name: '销量',
                // yAxisIndex: 1,
                type: 'bar',
                data: [20, 5, 18, 15, 5, 8],
            },
        ],
    }

    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option)

    // 接收消息后客户端处理方法
    ws.onmessage = function (evt) {
        const list = JSON.parse(evt.data)
        // console.log('list >> '，list)
        option.xAxis.data = list.map(item => item.name)
        option.series[0].data = list.map(item => item.price)
        option.series[1].data = list.map(item => item.num)
        myChart.setOption(option)
    }

    // 关闭websocket
    ws.onclose = function () {
        // 关闭 websocket
        console.log('关闭websocket')
    }
}
let userList = ref([])
// 获取登录日志
const getUserLog = async () => {
    const res = await axios({
        method: 'get',
        url: 'http://localhost:3000/operator/log',
    })
    const { code, info } = res.data
    if (code === 1) {
        userList.value = info.splice(0, 5)
        console.log(userList.value)
    }
}

// 商品销量排行
const goodRandList = ref([])

// 获取所有商品信息
const getAllList = async ()=>{
    const res = await axios({
        method: 'get',
        url: 'http://localhost:3000/goods/alllist',
    })
    const { code, info } = res.data
    if (code === 1) {
        let arr = []
        info.forEach(item=>{
            // if(goodRandList.value.length<)
            // goodRandList.value.push 
            arr.push(item.sales_volume)
        })
        info.forEach(item=>{
            if(item.sales_volume==arr.sort((a,b) => (b - a))[0]) {
                goodRandList.value.unshift(item)
            }
            if(item.sales_volume==arr.sort((a,b) => (b - a))[1]) {
                goodRandList.value.unshift(item)
            }
        })
        // .sort((a,b) => (a - b))
        console.log(goodRandList.value)
    }
}
// 
/**
 * vue组件 生命周期函数执行规则:
 *    vue生命周期created中启动异步任务，不会等待异步任务结果，在执行mounted生命周期函数，
 *    如果要在mounted生命周期使用数据，在mounted启动异步任务，接收数据处理后续操作
 */
onMounted(() => {
    getCategoryList()
    drawBar()
    getUserLog()
    getAllList()
})
</script>

<style lang="scss" scoped>
.row1 {
    .el-col {
        div {
            box-sizing: border-box;
            padding: 20px;
            border: 1px solid #e6e6e6;
            display: flex;
            align-items: center;
            span {
                min-width: 60px;
                .el-icon {
                    font-size: 40px;
                }
                p:first-of-type {
                    color: gray;
                }
            }
        }
    }
}
.row2 {
    margin-top: 10px;
    .el-col {
        div {
            border: 1px solid #e6e6e6;
        }
    }
}
.row3 {
    margin-top: 10px;
    .el-col {
        div {
            border: 1px solid #e6e6e6;
        }
    }
    .salesList{
        height: 300px;
        overflow: hidden;
        .salesBox{
            padding: 30px;
            padding-bottom: 5px;
            display: flex;
            .left{
                margin-right: 20px;
                border: none;
            }
            .right{
                border: none;
                div{
                    border: none;
                }

            }
        }
    }
}
</style>
